package de.dopichaj.labrador.inex.compare;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.commons.lang.Validate;
import org.apache.xml.resolver.tools.CatalogResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

/**
 * INEX hits contain the basic information about the results in the INEX
 * submission files.
 */
public final class InexHit {

    private final String fileName;
    private final String xPath;
    private final double rsv;
    
    public InexHit(String fileName, String xPath, double rsv) {
        
        Validate.notNull(fileName);
        Validate.notNull(xPath);
        this.fileName = fileName;
        this.xPath = xPath;
        this.rsv = rsv;
    }
    
    /**
     * Read an INEX submission file from the given stream.
     * @return a map from the topic ID to the ordered list of results.
     */
    public static Map<Integer, List<InexHit>>
        readInexSubmission(InputStream input)
        throws ParserConfigurationException, SAXException, IOException {
        
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setEntityResolver(new CatalogResolver());
        
        SubmissionHandler handler = new SubmissionHandler();
        xmlReader.setContentHandler(handler);
        xmlReader.parse(new InputSource(input));
        
        return handler.getResultMap();
    }

    public String getFileName() {
        return fileName;
    }

    public double getRsv() {
        return rsv;
    }

    public String getXPath() {
        return xPath;
    }

    @Override
    public String toString() {
        return "InexHit: " + fileName + "/" + xPath + "/" + rsv; 
    }
    
    @Override
    public int hashCode() {
        final int PRIME = 31;
        int result = 1;
        result = PRIME * result + fileName.hashCode();
        result = PRIME * result + xPath.hashCode();
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final InexHit other = (InexHit)obj;
        if (!fileName.equals(other.fileName))
            return false;
        if (!xPath.equals(other.xPath))
            return false;
        return true;
    }

    /**
     * Calculate the Levenshtein distance (edit distance) of two ordered
     * result lists.
     * @return the number of edit operations required to transform one list
     *          into the other
     */
    public static int levenshteinDistance(List<InexHit> hits1,
        List<InexHit> hits2) {
        
        Validate.notNull(hits1);
        Validate.notNull(hits2);
        
        int[] oldDistance = new int[hits2.size() + 1];
        int[] currentDistance = oldDistance;
        for (int i = 0; i < oldDistance.length; i++) {
            oldDistance[i] = i;
        }
        
        int pos1 = 1;
        for (InexHit hit1 : hits1) {
            
            currentDistance = new int[oldDistance.length];
            currentDistance[0] = pos1;
            
            int pos2 = 1;
            for (InexHit hit2 : hits2) {
                
                int cost;
                cost = hit1.equals(hit2) ? 0 : 1;
                currentDistance[pos2] = Math.min(oldDistance[pos2] + 1,
                    Math.min(currentDistance[pos2 - 1] + 1,
                        oldDistance[pos2 - 1] + cost));
                pos2++;
            }

            oldDistance = currentDistance;
            pos1++;
        }
        
        return currentDistance[currentDistance.length - 1];
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/